package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.OrderDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Setmeal> page = setmealDao.findPage(queryPageBean);
        return new PageResult(page.getTotal(), page.getResult());
    }
    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addGroupIdWithSetmealId(setmeal.getId(),checkgroupId);
            }
        }
        Jedis jedis = jedisPool.getResource();
        jedis.sadd(RedisConstant.SETMEAL_PIC_RESOURCES_DB,setmeal.getImg());

        generterMobileStaticHtml();
        jedis.close();

    }



    @Override
    public Setmeal findById(Integer id) {
        System.out.println(setmealDao.findById(id));
        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> getGroupIds(Integer id) {
        return setmealDao.getGroupIds(id);
    }


    @Override
    public void delete(Integer id,String img) {
        Jedis jedis = jedisPool.getResource();
        Setmeal setmeal = setmealDao.findById(id);
        jedis.srem(RedisConstant.SETMEAL_PIC_RESOURCES_DB,setmeal.getImg());
        setmealDao.delete_setmeal_checkgroup(id);
        setmealDao.delete(id);
        jedis.close();
        generterMobileStaticHtml();
    }


    @Override
    public void update(Setmeal setmeal, Integer[] checkgroupIds) {
        Setmeal setmeal1 = setmealDao.findById(setmeal.getId());
        String oldImg = setmeal1.getImg();
        String newImg = setmeal.getImg();
        Jedis jedis = jedisPool.getResource();
        jedis.srem(RedisConstant.SETMEAL_PIC_RESOURCES_DB,oldImg);
        jedis.sadd(RedisConstant.SETMEAL_PIC_RESOURCES_DB,newImg);
        setmealDao.delete_setmeal_checkgroup(setmeal.getId());
        if (checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.addGroupIdWithSetmealId(setmeal.getId(),checkgroupId);
            }
        }
        setmealDao.update(setmeal);
        //静态化页面
        generterMobileStaticHtml();
        jedis.close();
    }

    @Override
    public Setmeal findSetmealById(Integer id) {
        return setmealDao.findSetmealById(id);
    }

    @Override
    public Map findSetmealOrderNum() {
        List<String> setmealNames = new ArrayList();
        List<Map<String,Object>> setmealCount = setmealDao.findSetmealNameAndOrderCount();
        for (Map<String, Object> map : setmealCount) {
            setmealNames.add((String) map.get("name"));
        }
        Map<String,Object> map = new HashMap();
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",setmealCount);
        System.out.println(map);
        return map;
    }

    //获得热门（前4）套餐及预约人数
    @Override
    public List<Map<String, Object>> findHotSetmeal() {
        List<Map<String, Object>> list = setmealDao.findHotSetmealNameAndOrderCount();
        return list;
    }

    private void generterMobileStaticHtml() {
        List<Setmeal> list = setmealDao.findAll();
        if (list != null && list.size()>0){
            generterMobileSetmealListHtml(list);
            for (Setmeal setmeal : list) {
                generterMobileSetmealHtml(setmeal);
            }
        }
    }

    private void generterMobileSetmealHtml(Setmeal setmeal) {
        Map<String,Setmeal> map = new HashMap<>();
        map.put("setmeal",setmealDao.findSetmealById(setmeal.getId()));
        generterHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
    }

    private void generterMobileSetmealListHtml(List<Setmeal> list) {
        Map<String,List<Setmeal>> map = new HashMap<>();
        map.put("setmealList",list);
        generterHtml("mobile_setmeal.ftl","mobile_setmeal.html",map);
    }

    public void generterHtml(String templateName, String htmlPageName, Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        try {
            Template template = configuration.getTemplate(templateName);
            OutputStreamWriter ow = new OutputStreamWriter(new FileOutputStream(
                    new File(outPutPath +"/"+htmlPageName)),"UTF-8");
            template.process(map,ow);
            ow.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
